package cn.boy.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.boy.service.AdminstratorService;
import cn.boy.service.AdminstratorServiceFactory;
import cn.boy.service.StudentService;
import cn.boy.service.StudentServiceFactory;
import cn.boy.utils.Util;


public class LoginServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/**
		 * 	设置response使用的码表，以控制response以什么码表向浏览器写出数据
			response.setCharacterEncoding("UTF-8");
			指定顶浏览器以什么码表打开服务器发送的数据
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.setContentType("text/html;char=UTF-8");此代码可代替以上两句代码
		 */
		response.setContentType("text/html;charset=UTF-8");
		//获取到客户端传来的参数
		String no = request.getParameter("name");
		String password = request.getParameter("password");
		String role = request.getParameter("role");
		role = new String(role.getBytes("ISO-8859-1"),"UTF-8");
		
		System.out.println("no :" + no + ", password: "+ password + ", role:" + role);
		
		String json = "";
		
		if (!Util.isEmpty(no) && !Util.isEmpty(password) && !Util.isEmpty(role)) {
			if (role.equals("学生")) {
				StudentServiceFactory instance = StudentServiceFactory
						.getInstance();
				StudentService service = instance.getStudentService();
				json = service.login(no, password);
			} else {
				AdminstratorServiceFactory instance = AdminstratorServiceFactory
						.getInstance();
				AdminstratorService service = instance.getAdminstratorService();
				json = service.login(no, password);
			}
		}
		System.out.println("json --->>"+ json);
		
		if(!Util.isEmpty(json)){
			response.getOutputStream().write(json.getBytes("UTF-8"));
			return ;
		}
		response.getOutputStream().write("".getBytes("UTF-8"));
	
		
		
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
